# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging

from async.celery import app

from common.cache import redis_cache
from common.bank_record.model import BankRecord, RECORD_STATUS
from common.sms import db as sms_db
from common.order.db import add_order_success, add_sms_order_success, get_order
from common.mch import handler as mch_handler

_LOGGER = logging.getLogger('worker')


# @app.task(name='common.handler_order')
# def handler_order(record_id):
#     # print 'start'
#     _LOGGER.info('handler_order record_id: %s ,start', record_id)
#     item = BankRecord.query.filter(BankRecord.id == int(record_id)).filter(
#         BankRecord.status == RECORD_STATUS.UNMATCH).filter(BankRecord.payer.contains(u'支付宝')).first()
#     if item is None:
#         _LOGGER.info('handler_order item is none ')
#         return
#     order_id, amount = add_order_success(item.id, item.bankcard_name, item.amount)
#     _LOGGER.info('handler_order record_id: %s,  order_id: %s,  amount：%s', record_id, order_id, amount)
#     if order_id:
#         item.status = RECORD_STATUS.MATCHED
#         item.order_id = order_id
#         item.save()
#         mch_handler.notify_mch(order_id)
#         redis_cache.del_bank_card_special_amount(item.bankcard_name, amount, item.amount)
#         _LOGGER.info('handler_order record_id : %s, success', record_id)
#     # print 'end'


@app.task(name='common.handler_sms_order')
def handler_sms_order(sms_id):
    # print 'start'
    _LOGGER.info('handler_sms_order sms_id: %s ,start', sms_id)
    item = sms_db.get_unmatch_sms(sms_id)
    if item is None:
        _LOGGER.info('handler_sms_order item is none ')
        return
    bank_phones_from = ('95533', '95508', '95599', '95580', '95595')
    if item.from_phone not in bank_phones_from:  # 校验银行手机号
        _LOGGER.info('handler_sms_order from_phone is %s, not in 95533,95508,95599,95580,95595' % item.from_phone)
        return
    order_id, amount = add_sms_order_success(sms_id, item.bankcard_name, item.amount)
    _LOGGER.info('handler_sms_order record_id: %s,  order_id: %s,  amount：%s', sms_id, order_id, amount)
    if order_id:
        sms_db.match_sms(sms_id, order_id, 'auto')
        mch_handler.notify_mch(order_id)
        order = get_order(order_id)
        redis_cache.del_bank_card_special_amount(order.bankcard_num, order.real_amount)
        _LOGGER.info('handler_sms_order sms_id : %s, success', sms_id)
    # print 'end'
